package com.whty.cms.filewps.common.aspect;

import com.whty.cms.filewps.common.model.ControllMonitorLog;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@Aspect
//@Component
public class ControllerMonitorLog { 
	
	private static final Logger logger = LogManager.getLogger(ControllerMonitorLog.class);
	
	@Autowired
	private MongoOperations mongoOperations;
	
	@Around(value = "@annotation(org.springframework.web.bind.annotation.RequestMapping)", argNames="pjp")
	public Object afterController(ProceedingJoinPoint pjp) {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		RequestWrapper requestWrapper = new RequestWrapper(request);
		String responseBody = requestWrapper.getBody();
		Object[] args = pjp.getArgs();
		String methodName = pjp.getTarget().getClass().getSimpleName() + "." + pjp.getSignature().getName();
		Object result = null;
		try {
			long start = System.currentTimeMillis();
			result = pjp.proceed(args);
			long finish = System.currentTimeMillis();
            long useTime = finish - start;
            /** 接口响应时间监控 */
            ControllMonitorLog entity = new ControllMonitorLog();
            entity.setRequestParam(responseBody);
            
            entity.setHttpMethod(request.getMethod());
            entity.setUseTime(Integer.parseInt(String.valueOf(useTime)));
            entity.setRequestUrl(request.getRequestURI());
            entity.setRequestTime(new Date());
            mongoOperations.insert(entity,"cmsfile");
		}catch (Throwable e) {
			e.printStackTrace();
			logger.info(e.getMessage());
			System.out.println("【环绕通知中的--->异常通知】：the method 【" + methodName + "】 occurs exception " + e);
		}
		return result;
	}
}
